﻿using System.Text.Json;
using CoreLib;
using Domain.Repository.ResponseModels;

namespace UI.Extensions
{
    public static class ExtensionsUtil
    {
        public static List<T> ToTree<T>(this TaskNodeTreeT treeRoot) where T : TreeBase, new()
        {
            var resultList = new List<T>();

            resultList.Add(new T
            {
                TID = treeRoot.ID,
                TName = treeRoot.TX,
                TParentId = "0"
            });

            resultList.AddRange(GetCTreeList<T>(treeRoot));

            return resultList;
        }

        private static List<T> GetCTreeList<T>(TaskNodeTreeT data) where T : TreeBase, new()
        {
            var result = new List<T>();
            if (data != null)
            {
                var t = JsonSerializer.Serialize(data.T);
                if (t?[0] == '[')
                {
                    var tn = JsonSerializer.Deserialize<List<TaskNodeTreeT>>(t);
                    if (tn != null && tn.Count > 0)
                    {
                        foreach (var m in tn)
                        {
                            result.Add(new T
                            {
                                TID = m.ID,
                                TName = m.TX,
                                TParentId = data.ID
                            });
                            result.AddRange(GetCTreeList<T>(m));
                        };
                    }
                }
                else
                {
                    var ti = JsonSerializer.Deserialize<TaskNodeTreeT>(t ?? "null");
                    if (ti != null)
                    {
                        result.Add(new T
                        {
                            TID = ti.ID,
                            TName = ti.TX,
                            TParentId = data.ID
                        });
                        result.AddRange(GetCTreeList<T>(ti));
                    }
                }
            }
            return result;
        }

    }
}
